<?php

namespace app\common\model;

use think\Model;

use fast\Http;

use think\cache\driver\Redis;


class Order extends Model
{





    // 表名
    protected $name = 'order';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'status_text',
        'deliverytime_text',
        'createtime_text',
        'paytime_text',
        'taketime_text',
        'tpye_text',
        'pay_type_text',
        'is_examine_text'
    ];



    public function getStatusList()
    {
        return [
            '1' => __('待支付'),
            //            '2' => __('待发货'),

            '3' => __('已付款'),
            '4' => __('已完成'),
            '5' => __('已取消'),
            '8' => __('拼团中'),
            //            '6' => __('支付审核中'), '7' => __('支付失败')

        ];
    }

    public function getIsExamineList()
    {
        return ['1' => __('支付审核中'), '2' => __('支付审核成功'), '3' => __('支付失败')];
    }


    public function getIsExamineTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['is_examine']) ? $data['is_examine'] : '');
        $list = $this->getIsExamineList();
        return isset($list[$value]) ? $list[$value] : '';
    }



    public function getTpyeList()
    {
        return ['1' => __('Tpye 1'), '2' => __('Tpye 2'), '3' => __('Tpye 3')];
    }

    public function getPayTypeList()
    {
        return ['wechat' => __('Pay_type wechat'), 'alipay' => __('Pay_type alipay')];
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getDeliverytimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['deliverytime']) ? $data['deliverytime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getCreatetimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['createtime']) ? $data['createtime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getPaytimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['paytime']) ? $data['paytime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getTaketimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['taketime']) ? $data['taketime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getTpyeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['tpye']) ? $data['tpye'] : '');
        $list = $this->getTpyeList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getPayTypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['pay_type']) ? $data['pay_type'] : '');
        $list = $this->getPayTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    protected function setDeliverytimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setPaytimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setTaketimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }


    public function user()
    {
        return $this->belongsTo('User', 'user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


    public function company()
    {
        return $this->belongsTo('Company', 'company_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function ordergoods()
    {
        return $this->hasMany('app\common\model\order\Goods', 'order_id', 'id');
    }

    public function pay()
    {
        return $this->belongsTo('Paygoods', 'pay_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }





    // public function orderaddress()
    // {
    //     return $this->belongsTo('app\common\model\order\Address', 'order_id', 'id', [], 'LEFT')->setEagerlyType(0);

    // }

    public function backOrder($order_sn, $transaction_id = 0)
    {

        $order = model('app\common\model\Order')
            ->where('order_sn', $order_sn)
            ->where('status', 1)
            ->find();

        if (!$order) {
            return false;
        }
        $order->paytime = time();
        $order->transaction_id = $transaction_id;

        if ($order['tpye'] == 2) {
            $order->status = 8;
            $ordrGoods = \model('app\common\model\order\Goods')
                ->with(['sku', 'goods2'])
                ->where('order_id', $order['id'])
                ->find();

            //            $order['grouporder_id'] = 4;

            if ($order['grouporder_id'] > 0) { //有拼团

                $Grouporder = model('app\common\model\Grouporder')->where('id', $order['grouporder_id'])->find();
                // $now_use_num = $Grouporder->use_num+1;
                $Grouporder->use_num = $Grouporder->use_num - 1;
                if ($Grouporder->use_num <= 0) {
                    model('app\common\model\Order')
                        ->where('grouporder_id', $order['grouporder_id'])
                        ->update(['status' => 3]);
                    // $order->status = 3;
                    $Grouporder->status = 2;
                }

                $Grouporder->save();

                $insertUser = [
                    'user_id' => $order['user_id'],
                    'type' => 2,
                    'grouporder_id' => $order['grouporder_id'],
                    'order_id' => $order['id'],
                    'createtime' => time(),
                ];

                \model('app\common\model\Groupuser')->insert($insertUser);
            } else {
                $insert = [
                    'goods_id' => $ordrGoods['goods_id'],
                    'sku_id' => $ordrGoods['sku']['id'],
                    'use_num' => $ordrGoods['sku']['name'] - 1,
                    'group_num' => $ordrGoods['sku']['name'],
                    'createtime' => time(),
                    'user_id' => $order['user_id'],     //添加拼团团长
                ];

                $grouporder_id = \model('app\common\model\Grouporder')
                    ->insertGetId($insert);

                $insertUser = [
                    'user_id' => $order['user_id'],
                    'type' => 1,
                    'grouporder_id' => $grouporder_id,
                    'order_id' => $order['id'],
                    'createtime' => time(),
                ];
                //                var_dump($insertUser);exit();
                \model('app\common\model\Groupuser')->insert($insertUser);
            }

            //            dump($ordrGoods);exit();


            $order->save();
            //            return true;
        }

        if ($order['tpye'] == 1) {

            $order->status = 3;
            $order->save();
        }

        if ($order['tpye'] == 3) {
            $order->status = 3;
            $order->save();



            //            return true;
        }

        $user = model('app\common\model\User')->where('id', $order['user_id'])->find();

        if ($order->order_total > 0 && $user['recommend'] > 0) {

            $commisionlevel = model('app\admin\model\Commissionlevel')->find();
            $money = $order->order_total * $commisionlevel['level1'] / 100;
            $recommend2 = 0;
            //上级
            $user_recommend = model('app\common\model\User')->where('id', $user['recommend'])->find();
            $money2 = 0;
            if ($user_recommend && $user_recommend['recommend'] > 0) {
                $money2 = $order->order_total * $commisionlevel['level2'] / 100;
                //上上级
                $recommend2 = $user_recommend['recommend'];
            }
            $buy_id = $order['user_id'];
            model('app\common\model\User')::money($buy_id, $money, $user['recommend'], '直接上级分销佣金', 2, $recommend2, $money2);
        }
        // $order->send_goods = 1;
        $order->taketime = time();
        $order->deliverytime = time();
        $order->save();
        // $this->setOrderStatus($order->id,$order);
    }



    public function setOrderStatus($ids, $row)
    {




        // $row = $this->model->get($ids);
        if (!$row) {
            return;
        }

        $excode = 'sahnde';

        $openid = model('app\common\model\User')->where('id', $row['user_id'])->value('openid');

        $goodsName =  model('app\common\model\order\Goods')->where('order_id', $ids)->value('goods_name');

        // ,$row,$goodsName,$openid

        $Redis = new Redis();

        $key = 'access_token';

        $access_token = $Redis->get($key);



        if (!$access_token) {

            $config = get_addon_config('epay');

            $appId = $config['wechat']['miniapp_id'];

            $appSecret = $config['wechat']['app_secret'];

            // 		$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appId&secret=$appSecret";

            $params = [
                'appid' => $config['wechat']['miniapp_id'],
                'secret' => $config['wechat']['app_secret'],

            ];

            $res = Http::sendRequest("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential", $params, 'GET');

            $access_token = json_decode($res['msg'], 1);

            $access_token = $access_token['access_token'];


            if ($access_token) {

                $Redis->set($key, $access_token, 7100);
            }
        }


        $url = 'https://api.weixin.qq.com/wxa/sec/order/upload_shipping_info?access_token=' . $access_token;
        $datas = '{
                "order_key": {
                    "order_number_type": 2,
                    "transaction_id": "' . $row['transaction_id'] . '"
                },
                    "delivery_mode": 1,
                    "logistics_type": 4,
                    "shipping_list": [
                        {
                            "tracking_no": "' . 'SN' . time() . rand(1000, 9999) . '",
                            "express_company": "' . $excode . '",
                            "item_desc": "' . $goodsName . '",
                            "contact": {
                                "consignor_contact": "177****1234"
                            }
                        }
                    ],
                    "upload_time": "' . date(DATE_RFC3339) . '"' . ',
                    "payer": {
                        "openid": "' . $openid . '"
                    }
                }
            ';

        $request  = $this->https_request($url, $datas);

        // 	  \think\Log::record('=========='.$request);

        $request = json_decode($request, true);

        if ($request['errmsg'] == 'ok') {

            return true;
        } else {
            return false;
        }
    }

    public function https_request($url, $data = null)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }


//    关联拼团订单表
    public function grouporder()
    {
        return $this->belongsTo('app\common\model\Grouporder', 'grouporder_id','id');
    }
}
